package tiled.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.prefs.Preferences;

public final class TiledConfiguration
{
    public static final int RECENT_FILE_COUNT = 8;

    private static final Preferences prefs = Preferences.userRoot().node("tiled");

    private TiledConfiguration()
    {   
    }

    public static Preferences node(String pathName)
    {
        return prefs.node(pathName);
    }

    public static Preferences root()
    {
        return prefs;
    }

    public static void addToRecentFiles(String mapFile)
    {
        assert mapFile != null;

        List<String> recent = getRecentFiles();

        Iterator iterator = recent.iterator();
        while(iterator.hasNext())
        {
            String filename = (String)iterator.next();
            if (filename.equals(mapFile))
            {
                iterator.remove();
            }
        }

        recent.add(0, mapFile);

        Preferences recentNode = prefs.node("recent");
        for (int i = 0; i < RECENT_FILE_COUNT && i < recent.size(); i++)
        {
            String recentFile = recent.get(i);
            recentNode.put("file" + i, recentFile);
        }
    }

    public static List<String> getRecentFiles()
    {
        List<String> recent = new ArrayList<String>(RECENT_FILE_COUNT);
        Preferences recentNode = prefs.node("recent");
        for (int i = 0; i < RECENT_FILE_COUNT; i++)
        {
            String recentFile = recentNode.get("file" + i, "");
            if (recentFile.length() > 0)
            {
                recent.add(recentFile);
            }
        }
        return recent;
    }

    public static String fileDialogStartLocation()
    {
        return node("recent").get("file0", null);
    }
}
